package com.zmj.demo.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.demo.pojo.entity.req.RequestParam;
import com.zmj.framework.base.controller.BaseController;
import com.zmj.framework.request.PageRequest;
import com.zmj.framework.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zmj.demo.pojo.entity.PageEntity;
import com.zmj.demo.service.PageService;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zmj.org
 * @since 2024-04-08
 */
@RestController
@Api(tags = { "PageEntity" })
@RequestMapping("/v1/api/pageEntity")
public class PageController extends BaseController<PageService, PageEntity> {

    @Autowired
    private PageService pageService;

    @ApiOperation(value = "添加")
    @Operation(summary = "添加", description = "添加")
    @PostMapping(value = "/add")
    @Override
    public Result<PageEntity> add(@Valid @RequestBody PageEntity pageEntity) {
        baseService.saveOrUpdate(pageEntity);
        return Result.success(pageEntity);
    }

    @ApiOperation(value = "根据id修改")
    @Operation(summary = "根据id修改", description = "根据id修改")
    @PutMapping(value = "/update")
    @Override
    public Result<PageEntity> update(@Valid @RequestBody PageEntity pageEntity) {
        Assert.notNull(pageEntity.getId(), "id不能为空");
        return super.update(pageEntity);
    }

    @ApiOperation(value = "根据id批量删除")
    @Operation(summary = "根据id批量删除", description = "根据id批量删除")
    @PostMapping(value = "/deleteByIds")
    public Result<?> deleteByIds(@RequestBody RequestParam requestParam) {
        String ids = requestParam.getIds();
        Assert.notBlank(ids,"ids不能为空！");
        return Result.success(pageService.removeBatchByIds(Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList())));
    }

    @ApiOperation(value = "分页查询")
    @Operation(summary = "分页查询", description = "分页查询")
    @PostMapping("/pageList")
    public Result<IPage<PageEntity>> pageList(@RequestBody PageRequest pageRequest) {
        Map<String, Object> param = pageRequest.getParam() == null ? new HashMap<>() : pageRequest.getParam();
        param.put("order",pageRequest.getOrder());
        param.put("orderBy",pageRequest.getOrderBy());
        IPage<PageEntity> page = new Page<>(pageRequest.getPageInfo().getPageIndex(), pageRequest.getPageInfo().getPageSize());
        return Result.success(pageService.pageList(page, param));
    }
}
